package org.cn.zhaozhx.util;

import java.io.IOException;

import org.mozilla.universalchardet.UniversalDetector;

/**
 * 文件编码自动检测
 * 
 * @author flying
 * 
 */
public class FileCharsetInfo {
    
    /**
     * 文件编码自动检测
     * 
     * @param fileName
     *            要检测的文件名
     * @return 文件编码
     * @throws IOException
     */
    public static String getFileCharSet(String fileName) throws IOException {
        
        byte[] buf = new byte[4096];
        java.io.FileInputStream fis = new java.io.FileInputStream(fileName);
        
        // (1)
        UniversalDetector detector = new UniversalDetector(null);
        
        // (2)
        int nread;
        while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }
        // (3)
        detector.dataEnd();
        
        // (4)
        String encoding = detector.getDetectedCharset();
        if (encoding != null) {
            // System.out.println("Detected encoding = " + encoding);
        } else {
            // System.out.println("No encoding detected.");
        }
        
        // (5)
        detector.reset();
        return encoding;
    }
    
}